import base64
import re

import rsa


# # 生成公钥和私钥，密钥长度为 2048 位
# (pubkey, privkey) = rsa.newkeys(2048)
#
# # 保存公钥到文件
# with open('data/public.pem', 'wb') as f:
#     f.write(pubkey.save_pkcs1())
#
# # 保存私钥到文件
# with open('data/private.pem', 'wb') as f:
#     f.write(privkey.save_pkcs1())


def rsa_encode(content):
    content = str(content).encode()
    # 从文件加载公钥
    with open('data/public.pem', 'rb') as f:
        pubkey = rsa.PublicKey.load_pkcs1(f.read())
    value = rsa.encrypt(content, pubkey)
    value = base64.b64encode(value).decode()
    return value


def rsa_decode(content):
    content = base64.b64decode(content.encode())
    # 从文件加载私钥
    with open('data/private.pem', 'rb') as f:
        privkey = rsa.PrivateKey.load_pkcs1(f.read())
    value = rsa.decrypt(content, privkey)
    value = value.decode()
    return value


s = "adm#@￥5*……in123?!@$$%asdf好好"
print("原文：" + s)
ss = rsa_encode(s)
print("加密：" + ss)
sss = rsa_decode(ss)
print("译文：" + sss)
print(s == sss)

data_str ="""data:
  password: ${md5(123)},
  username: ${md5(admin)},
method: post
url: http://116.62.63.211:5000/md5login
"""
func_name = 'md5'
r = ('md5', '123')
func_result = "aaaaaaa"
a = "${" + f"{func_name}(" + r[1] + ")}"
print(a)
a = "${" + func_name + "(" + r[1] + ")}"
print(a)
print("原来"+data_str)
data_str = data_str.replace(a, str(func_result))

print("替换"+data_str)
